//
//  TDAnchorView.m
//  liveDemo
//
//  Created by tuandai on 2017/4/17.
//  Copyright © 2017年 tuandai. All rights reserved.
//

#import "TDAnchorView.h"
#import <TXRTMPSDK/TXLivePush.h>
#import "TDBeautyView.h"
#import "TDChatTableViewCell.h"
#import "TDChatToolView.h"
#import "TCMsgHandler.h"
#import "TCMsgBulletView.h"
#import "TDGiveGoodView.h"

@interface TDAnchorView ()<TDBeautyViewDelegate,UITableViewDataSource,UITableViewDelegate,TDChatToolViewDelegate,AVIMMsgListener>
@property (weak, nonatomic) IBOutlet UIButton *micBtn;
@property (nonatomic, strong) TDBeautyView *beautyView;
@property (weak, nonatomic) IBOutlet UITableView *chatTableView;
@property (nonatomic, assign) BOOL isFlash;
// no - 前置摄像头  yes - 后置摄像头
@property (nonatomic, assign) BOOL camera_switch;
// 美颜
@property (nonatomic, assign) float beauty_level;
// 美白
@property (nonatomic, assign) float whitening_level;
// 眼
@property (nonatomic, assign) float eye_level;
// 瘦脸
@property (nonatomic, assign) float face_level;
// 聊天数组
@property (nonatomic, strong) NSMutableArray *chatArr;
// 键盘工具栏
@property (nonatomic, strong) TDChatToolView *chatToolView;
// 是否打开了弹幕
@property (nonatomic, assign) BOOL isOpenBarrage;
// 用来点击编辑结束
@property (nonatomic, strong) UIView *coverView;
// 弹幕的父view
@property (weak, nonatomic) IBOutlet UIView *bulletSupView;
// 弹幕view
@property (nonatomic, strong) TCMsgBulletView *bulletViewOne;
@property (nonatomic, strong) TCMsgBulletView *bulletViewTwo;
// 点赞区域
@property (weak, nonatomic) IBOutlet TDGiveGoodView *giveGoodView;

@end

@implementation TDAnchorView

static NSString *cellID = @"TDAnchorViewID";
static NSInteger chatToolViewHeight = 64;

+(instancetype)createView {
    
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil].firstObject;
}

-(void)dealloc {
    TDLog(@"当前聊天view销毁了");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)awakeFromNib {
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    self.backgroundColor = [UIColor clearColor];
    [self.chatTableView registerNib:[UINib nibWithNibName:@"TDChatTableViewCell" bundle:nil] forCellReuseIdentifier:cellID];
    
    [self setObjectNature];
    
    self.chatToolView.hidden = YES;
 
    self.bulletViewOne.frame = CGRectMake(0, 0, Main_Screen_Width, 34);
    self.bulletViewTwo.frame = CGRectMake(0, CGRectGetMaxY(self.bulletViewOne.frame) + 10, Main_Screen_Width, 34);
    self.bulletViewOne.backgroundColor = [UIColor blueColor];
    self.bulletViewTwo.backgroundColor = [UIColor blueColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverViewClick)];
    [self.coverView addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(giveGoodViewClick)];
    [self.giveGoodView addGestureRecognizer:tap1];
    
}

- (void)setObjectNature {
    self.chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.chatTableView.estimatedRowHeight = 30;
    
    self.chatToolView.frame = CGRectMake(0, Main_Screen_Height + chatToolViewHeight, Main_Screen_Width, chatToolViewHeight);
    
//    self.chatTableView.bounces = NO;
    self.chatTableView.showsVerticalScrollIndicator = NO;
}

-(void)layoutSubviews {
    [super layoutSubviews];
}

-(void)setMsgHandler:(AVIMMsgHandler *)msgHandler {
    _msgHandler = msgHandler;
    if (!_msgHandler.roomIMListener) {
        _msgHandler.roomIMListener = self;
    }    
}

- (void)coverViewClick {
    [self endEditing:YES];
}



#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.chatArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TDChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.chatModel = self.chatArr[indexPath.item];
    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    return cell;
}

#pragma mark - 发送消息
- (void)btnSendText:(UITextField*)textField {
    NSString *pic = @"http://touxiang.qqzhi.com/uploads/2012-11/1111005600464.jpg";
    NSString *uid = @"用户id";
    NSString *uname = @"姓名";
    
    
    IMUserAble *able = [IMUserAble new];
    able.msg = textField.text;
    able.nickName = uname;
    able.userId = uid;
    if (self.isOpenBarrage) {
        [self.msgHandler sendDanmakuMessage:uid nickName:uname headPic:pic msg:textField.text];
        able.cmdType = AVIMCMD_Custom_Danmaku;
    }else {
        [self.msgHandler sendTextMessage:uid nickName:uname headPic:pic msg:textField.text];
        able.cmdType = AVIMCMD_Custom_Text;
    }
    [self onRecvGroupSender:able textMsg:nil];
}

#pragma mark - 弹幕信息
-(void)bulletMsg:(IMUserAble *)msgModel{
    if (msgModel.cmdType == AVIMCMD_Custom_Danmaku) {
        int random = arc4random_uniform(2);
        TDLog(@"%d",random);
        if (random) {
            [self.bulletViewOne bulletNewMsg:msgModel];
        }else {
            [self.bulletViewTwo bulletNewMsg:msgModel];
        }
//        if ([self getLocation:self.bulletViewOne] >= [self getLocation:self.bulletViewTwo]) {
//            [self.bulletViewTwo bulletNewMsg:msgModel];
//        }else{
//            [self.bulletViewOne bulletNewMsg:msgModel];
//        }
    }
    
    if (msgModel.cmdType == AVIMCMD_Custom_EnterLive || msgModel.cmdType == AVIMCMD_Custom_ExitLive) {
//        [_audienceTableView refreshAudienceList:msgModel];
    }
}

#pragma mark - 点赞
- (void)giveGoodViewClick {
    NSString *pic = @"http://touxiang.qqzhi.com/uploads/2012-11/1111005600464.jpg";
    NSString *uid = @"用户id";
    NSString *uname = @"姓名";
    BOOL temp = [self.msgHandler sendLikeMessage:uname nickName:uid headPic:pic];
    if (temp) {
        [self.giveGoodView addGoodAnimate];
    }
    
}


-(CGFloat)getLocation:(TCMsgBulletView *)bulletView{
    UIView *view = bulletView.lastAnimateView;
    CGRect rect = [view.layer.presentationLayer frame];
    return rect.origin.x + rect.size.width;
}

#pragma mark - 群组信息回调
-(void)onRecvGroupSender:(IMUserAble *)info textMsg:(NSString *)msg {
    if (info.cmdType == AVIMCMD_Custom_Text) { // 文本消息
        [self.chatArr addObject:info];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatArr.count - 1 inSection:0];
        
        [self.chatTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//        [self.chatTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }else if (info.cmdType == AVIMCMD_Custom_EnterLive) { // 用户加入直播
        
    }else if (info.cmdType == AVIMCMD_Custom_ExitLive) { // 用户退出直播
        
    }else if (info.cmdType == AVIMCMD_Custom_Like) { // 点赞消息
        [self.giveGoodView addGoodAnimate];
//        [self.chatArr addObject:info];
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatArr.count - 1 inSection:0];
//        
//        [self.chatTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }else if (info.cmdType == AVIMCMD_Custom_Danmaku) { // 弹幕消息
        [self bulletMsg:info];
        [self.chatArr addObject:info];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.chatArr.count - 1 inSection:0];
        
        [self.chatTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }else if (info.cmdType == AVIMCMD_Custom_Gift) { // 礼物信息
        
    }
}

- (void)onRecvGroupSystemMessage:(TIMGroupSystemElem *)msg {
    
}

#pragma mark - 开关麦克风
- (IBAction)micBtnClick:(UIButton *)sender {
    [self.txLivePublisher setMute:_isOpenMic];
    _isOpenMic = !_isOpenMic;
    if (_isOpenMic) {
        [self.micBtn setTitle:@"关闭麦克风" forState:(UIControlStateNormal)];
    }else {
        [self.micBtn setTitle:@"打开麦克风" forState:(UIControlStateNormal)];
    }
}

#pragma mark - 开关弹幕
- (void)barrageSwitch:(BOOL)isOpen {
    _isOpenBarrage = isOpen;
    if (isOpen) { // 发送弹幕
        
    }else {
        
    }
    
}





- (IBAction)chatBtnClick:(UIButton *)sender {
    [self.chatToolView.chatTextTield becomeFirstResponder];
}

#pragma mark - 前后摄像头
- (IBAction)cameraBtnClick:(UIButton *)sender {
    [self.txLivePublisher switchCamera];
}


#pragma mark - 闪光灯
- (IBAction)flashBtnClick:(UIButton *)sender {
    if (self.txLivePublisher.frontCamera) {
        [SVProgressHUD showErrorWithStatus:@"请切换后置镜头再打开闪光灯"];
    }else {
        self.isFlash = !self.isFlash;
        [self.txLivePublisher toggleTorch:self.isFlash];
        
    }
}

#pragma mark - 美颜
- (IBAction)beautyBtnClick:(UIButton *)sender {
    UISlider *s1 = self.beautyView.sliderArr[0];
    UISlider *s2 = self.beautyView.sliderArr[1];
    UISlider *s3 = self.beautyView.sliderArr[2];
    UISlider *s4 = self.beautyView.sliderArr[3];
    
    s1.value = self.eye_level;
    s2.value = self.face_level;
    s3.value = self.beauty_level;
    s4.value = self.whitening_level;
    
    self.beautyView.hidden = NO;
}

#pragma mark - 美颜进度条
-(void)slidersValueChange:(UISlider *)sender {
    if (sender.tag == 0) { // 大眼
        self.eye_level = sender.value;
        [self.txLivePublisher setEyeScaleLevel:self.eye_level];
    }else if (sender.tag == 1) { // 瘦脸
        self.face_level = sender.value;
        [self.txLivePublisher setFaceScaleLevel:self.face_level];
    }else if (sender.tag == 2) { // 美颜
        self.beauty_level = sender.value;
        [self.txLivePublisher setBeautyFilterDepth:self.beauty_level setWhiteningFilterDepth:self.whitening_level];
    }else if (sender.tag == 3) { // 美白
        self.whitening_level = sender.value;
        [self.txLivePublisher setBeautyFilterDepth:self.beauty_level setWhiteningFilterDepth:self.whitening_level];
    }
}

#pragma mark - 键盘显示、隐藏
-(void)keyBoardShow:(NSNotification*)info {
    NSDictionary *dict = info.userInfo;
    NSValue *value = [dict objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect rect = value.CGRectValue;
    self.chatToolView.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.chatToolView.frame = CGRectMake(0, rect.origin.y - chatToolViewHeight, Main_Screen_Width, chatToolViewHeight);
    } completion:^(BOOL finished) {
        self.coverView.frame = CGRectMake(0, 0, Main_Screen_Width, CGRectGetMinY(self.chatToolView.frame));
        self.coverView.hidden = NO;
    }];
}

#pragma mark - 关闭房间
-(void)closeRoom {
    [_msgHandler releaseIMRef];
    [self.giveGoodView closeRoom];
    [_bulletViewOne stopAnimation];
    [_bulletViewTwo stopAnimation];
}

-(void)keyBoardHidden:(NSNotification*)info {
    [UIView animateWithDuration:0.25 animations:^{
        self.chatToolView.frame = CGRectMake(0, Main_Screen_Height + chatToolViewHeight, Main_Screen_Width, chatToolViewHeight);
    } completion:^(BOOL finished) {
        self.chatToolView.hidden = YES;
        self.coverView.hidden = YES;
    }];
}

#pragma mark - 懒加载
-(TDBeautyView *)beautyView {
    if (!_beautyView) {
        _beautyView = [TDBeautyView createView];
        _beautyView.delegate = self;
        [self addSubview:_beautyView];
        
        [_beautyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
    }
    return _beautyView;
}

-(NSMutableArray *)chatArr {
    if (!_chatArr) {
        _chatArr = [NSMutableArray array];
    }
    return _chatArr;
}

-(TDChatToolView *)chatToolView {
    if (!_chatToolView) {
        _chatToolView = [TDChatToolView createView];
        _chatToolView.delegate = self;
        [self addSubview:_chatToolView];
        
    }
    return _chatToolView;
}

-(UIView *)coverView {
    if (!_coverView) {
        _coverView = [UIView new];
        _coverView.backgroundColor = [UIColor clearColor];
        [self addSubview:_coverView];
    }
    return _coverView;
}

-(TCMsgBulletView *)bulletViewOne {
    if (!_bulletViewOne) {
        _bulletViewOne = [TCMsgBulletView new];
        [self.bulletSupView addSubview:_bulletViewOne];
    }
    return _bulletViewOne;
}

-(TCMsgBulletView *)bulletViewTwo {
    if (!_bulletViewTwo) {
        _bulletViewTwo = [TCMsgBulletView new];
        [self.bulletSupView addSubview:_bulletViewTwo];
    }
    return _bulletViewTwo;
}

@end
